<?php
class Util
{
	public static function now()
	{
		return date('Y-m-d H:i:s');
	}
	
	public static function today()
	{
		return date('Y-m-d');
	}
	
	public static function isToday($date)
	{
		if(!is_numeric($date))
		{
			$date = strtotime($date);
		}
		
		if(Util::today()!=date('Y-m-d', $date))
		{
			return false;
		}
		
		return true;
	}
	
    public static function ip2number($ip)
    {
		$t	= explode('.',$ip);
		$x	= 0;
		for($i=0;$i<4;$i++)
		{
			$x 	= $x*256+$t[$i];
		}
		return $x;
	}
	
	public static function number2ip($num)
	{
		$t	= $num;
		$a	= array();
		for($i = 0;$i < 4;$i++)
		{
			$x				= $t % 256;
			if($x<0)
				$x	+= 256;
			array_unshift($a, $x);
			$t 	= intval($t/256);
		}
		return implode('.',$a);
	}
	
	public static function groupData($rows, $groupBy=false, $array=false)
	{
		if(!$groupBy || !$rows)
		{
			return $rows;
		}
		
		$ret	= array();
		foreach($rows as $row)
		{
			$tmp	= &$ret;
			$len	= count($groupBy);
			for($i=0;$i<$len;$i++)
			{
				$gbk	= $groupBy[$i];
				if($i<$len-1)
				{
					${$tmp}[$row[$gbk]]	= array();
					$tmp				= &$tmp[$row[$gbk]];
				}
				else
				{
					if($array)
					{
						if(!array_key_exists($row[$gbk], $tmp))
						{
							$tmp[$row[$gbk]]	= array();
						}
						$tmp[$row[$gbk]][]	= $row;
					}
					else
					{
						$tmp[$row[$gbk]]	= $row;
					}
				}
			}
		}
		
		return $ret;
	}
	
	public static function getFileExt($f)
	{
		return trim(substr(strrchr($f, '.'), 1, 10));
	}
	
	public static  function random($length, $numeric = 0)
	{
		PHP_VERSION < '4.2.0' && mt_srand((double)microtime() * 1000000);
		if($numeric)
		{
			$hash = sprintf('%0'.$length.'d', mt_rand(0, pow(10, $length) - 1));
		}
		else
		{
			$hash 	= '';
			$chars 	= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz';
			$max 	= strlen($chars) - 1;
			for($i = 0; $i < $length; $i++)
			{
				$hash 	.= $chars[mt_rand(0, $max)];
			}
		}
		return $hash;
	}
	
	public static function generatePassword($password,$secques)
	{
		return md5(md5($password).$secques);
	}
	
	public static function parseIds($key,$list)
	{
		if(empty($list))
		{
			return false;
		}
		
		$ret = array();
		foreach($list as $lv)
		{
			$ret[] = $lv[$key];
		}
		
		return $ret;
	}
	
	public static function getEncodeImg($str)
	{
		return base64_encode($str);
	}
	
	public static function getDirFiles($d)
	{
		if(function_exists('scandir'))
		{
			return scandir($d);
		}
		$dh  = opendir($d);
		while (false !== ($filename = readdir($dh)))
		{
			$files[] = $filename;
		}
		closedir($dh);
	
		return $files;
	}
	
	public static function getDefaultArray($element, $arr)
	{
		$num	= count($arr);
		for($i=$num-1;$i>=0;$i--)
		{
		if($arr[$i]==$element)
		{
		unset($arr[$i]);
		}
		}
		array_unshift($arr,$element);
		return $arr;
	}
	
	public static function loadSetting($key)
	{
		$settings = C('LtCache')->get('setting');
		if($settings === false)
		{
			$settings = self::reloadSetting();
		}
		
		if(!array_key_exists($key, $settings)){
			return false;
		}
		
		return $settings[$key];
	}
	
	public static function reloadSetting()
	{
		$settingDb = new Api('setting');
		$settings = $settingDb->fetchRows();
		$data = array();
		if(!empty($settings))
		{
			//添加到config中
			foreach($settings as $setting)
			{
				$val = json_decode($setting['sval'],true);
				if(is_null($val))
				{
					$val = $setting['sval'];
				}
				$data[$setting['skey']] = $val;
			}
		}
		
		if(!empty($data))
		{
			C('LtCache')->update('setting', $data);
		}
		
		return $data;
	}
	
	public static function updateSetting($settings,$updateConfig=true)
	{
		$settingDb = new Api('setting');
		foreach($settings as $k=>$v)
		{
			if(is_array($v))
			{
				$v = json_encode($v);
			}
			
			if($settingDb->fetch('',array('skey'=>'eq:'.$k)))
			{
				//已经有对应的记录在，更新
				$settingDb->updateRows(array('skey'=>'eq:'.$k), array('sval'=>$v));
			}
			else
			{
				//新增一条记录
				$settingDb->insert(array('skey'=>$k,'sval'=>$v));
			}
		}
	
		if($updateConfig)
		{
			self::reloadSetting();
		}
	}
	
	public static function loadSystemData()
	{
		//从内存中加载，如果多次调用，只读一次缓存文件
		$memcache = new MemoryCache();
		$system = $memcache->get('system');
		if($system!==false)
		{
			return $system;
		}
		
		//从缓存中加载
		$system = C('LtCache')->get('system');
		if($system !== false)
		{
			$memcache->set('system', $system);
			return $system;
		}
		
		$system = self::reloadSystem();
		if($system!==false)
		{
			$memcache->set('system', $system);
		}
		
		return $system;
	}
	
	private static function reloadSystem()
	{
		$data = array();
		
		//加载广告
		$template = Util::loadSetting('template');
		$adService = new BaseDbService('ad');
		$ads = $adService->rows(array('template'=>'eq:'.$template),'orderby DESC,id ASC');
		if(!empty($ads))
		{
			$adPositionService = new BaseDbService('ad_position');
			$adPositions = $adPositionService->rows(array('template'=>'eq:'.$template),'id ASC');
			$adPositions = Util::groupData($adPositions, array('id'));
			
			$tmp = array();
			foreach($ads as $ad)
			{
				if(!array_key_exists($ad['position'], $adPositions))
				{
					continue;
				}
				
				$position = $adPositions[$ad['position']]['position'];
				
				if(!array_key_exists($position, $tmp))
				{
					$tmp[$position] = array();
				}
				
				$tmp[$position][] = $ad;
			}
			
			$data['ad'] = $tmp;
		}
		
		//TODO
		
		//写缓存
		if(!empty($data))
		{
			C('LtCache')->update('system', $data);
		}
		
		return $data;
	}
	
	/**
	 * 获取指定时间与当前时间的时间间隔
	 *
	 * @access  public
	 * @param   integer      $time
	 *
	 * @return  string
	 */
	function getBeforeTimelag($time)
	{
		if($time == 0)
			return "";
		
		static $today_time = NULL,
				$before_lang = NULL,
				$beforeday_lang = NULL,
				$today_lang = NULL,
				$yesterday_lang = NULL,
				$hours_lang = NULL,
				$minutes_lang = NULL,
				$months_lang = NULL,
				$date_lang = NULL,
				$sdate = 86400;
		if($today_time === NULL)
		{
			$today_time = time();
			$before_lang = '前';
			$beforeday_lang = '前天';
			$today_lang = '今天';
			$yesterday_lang = '昨天';
			$hours_lang = '小时';
			$minutes_lang = '分钟';
			$months_lang = '月';
			$date_lang = '日';
		}
		
		$now_day = strtotime(date("Y-m-d", $today_time)); //今天零点时间 
		$pub_day = strtotime(date("Y-m-d", $time)); //发布期零点时间

		$timelag = $now_day - $pub_day;
		
		$year_time = date('Y', $time);
		$today_year = date('Y', $today_time);
		
		if($year_time < $today_year)
			return date('Y:m:d H:i', $time);
			
		$timelag_str = date(' H:i', $time);
		
		$day_time = 0;
		if($timelag / $sdate >= 1)
		{
			$day_time = floor($timelag / $sdate);
			$timelag = $timelag % $sdate;
		}
		
		switch($day_time)
		{
			case '0':
				$timelag_str = $today_lang.$timelag_str;
			break;
			
			case '1':
				$timelag_str = $yesterday_lang.$timelag_str;
			break;
			
			case '2':
				$timelag_str = $beforeday_lang.$timelag_str;
			break;
			
			default:
				$timelag_str = date('m'.$months_lang.'d'.$date_lang.' H:i', $time);
			break;
		}
		return $timelag_str;
	}

}
?>